package com.yxuan.springboot.controller;

import com.yxuan.springboot.model.TestTypeDetails;
import com.yxuan.springboot.service.TestTypeDetailsService;
import com.yxuan.springboot.util.COSImage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.*;


/**
 * @author zchao
 * TestTypeDetails控制器
 * @date 2023-05-16 14:22:56
 */
@Controller
@Slf4j
@Api(tags = "")
@RequestMapping(value = "/testtypedetails", method = {RequestMethod.POST, RequestMethod.GET})
public class TestTypeDetailsController extends BaseController<TestTypeDetails> {

    @Autowired
    private TestTypeDetailsService testTypeDetailsService;

    //测试首页
    @ResponseBody
    @RequestMapping(value = "/testhome", method = RequestMethod.GET)
    public HashMap<String, Object> testHome(@RequestBody Map map) throws Exception {
        return testTypeDetailsService.testHome(map);
    }

    //    查询所有测试类型,,,,,添加分页
    @RequestMapping(value = "/alltype", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> allType(@RequestBody Map map) {
        try {
            int page = (int) map.get("page");
            int limit = (int) map.get("limit");
            TestTypeDetails testTypeDetails = new TestTypeDetails();
            Map<String, Object> listByPramas = testTypeDetailsService.findListByPramas(page, limit, testTypeDetails);
            return listByPramas;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }
    }

    //    TODO 添加测试类型,只管添加就行

    @RequestMapping(value = "/addtype", method = RequestMethod.POST)
    @ResponseBody
    public HashMap<String, Object> addType(@RequestBody TestTypeDetails entity) {
        try {
            HashMap<String, Object> result = new HashMap<>();
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            entity.setCreateTime(timestamp);
            entity.setUpdateTime(timestamp);
            entity.setJoinNum(0);
            entity.setHot("0");
            testTypeDetailsService.save(entity);
            result.put("add", "success");
            return result;
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }

    }


    //   TODO 修改测试类型，看是否修改图片，若修改，则看之前是否存在图片，若存在，则删除原本的图片，再添加新的；
//              若之前不存在图片，则直接添加。
    @RequestMapping(value = "/updatetype", method = RequestMethod.POST)
    public HashMap<String, Object> updPic(@RequestBody TestTypeDetails entity) {
        try {
            //         1.是否修改图片
            if (entity.getPic() != null) {
                TestTypeDetails tById = testTypeDetailsService.findTById(String.valueOf(entity.getId()));
//            之前有图片
                if (tById.getPic() != null) {
                    //                删除原本存储在腾讯云的图片
//                获取文件名
                    String url = tById.getPic();
                    URL url1 = new URL(url);
                    String path = url1.getPath();
                    String substring = path.substring(path.lastIndexOf('/') + 1);
                    COSImage cosImage = new COSImage();
//                url = "腾讯云文件夹名+文件名"
                    String url2 = "zypic/" + substring;
                    cosImage.deleteFile(url2);
                }
            }
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            entity.setUpdateTime(timestamp);
            return testTypeDetailsService.updPic(entity);
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;

        }
    }


    //  测试详情界面
    @ResponseBody
    @RequestMapping(value = "/testdetils", method = RequestMethod.POST)
    public HashMap<String, Object> prepareTest(@RequestBody TestTypeDetails testTypeDetails) {
        try {
            return testTypeDetailsService.prepareTest(testTypeDetails.getId());
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }

    }

    //    查看测试结果
    @ResponseBody
    @RequestMapping("/testscore")
    public HashMap<String, Object> testScore(@RequestBody Map map) {
        try {
            Integer recordid = (Integer) map.get("recordid");
            return testTypeDetailsService.testScore(recordid);
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }
    }


//    上传图片（仅jpg和png）

    @PostMapping("/upload")
    @ResponseBody
    public HashMap<String, Object> handleImgUpload(MultipartFile file) throws IOException {
//        获取上传文件信息
        try {
            HashMap<String, Object> result = new HashMap<>();
            if (file != null) {
                String filename;
                String originalFilename = file.getOriginalFilename();
                String contentType = file.getContentType();
                long size = file.getSize();
                String localPath = System.getProperty("user.dir") + "/src/main/resources/img/type";
//        根据文件名获取文件后缀名
                String suffixName = contentType.substring(contentType.indexOf("/") + 1);
                //            只允许上传图片，若上传非图片，提醒上传图片
                if (!suffixName.equals("png") && !suffixName.equals("jpeg") && !suffixName.equals("jpg")) {
                    result.put("error", "上传不是png或jpg");
                    return result;
                }
//            得到文件名
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                filename = uuid + "." + suffixName;
                COSImage cosImage = new COSImage();
//            文件保存路径
                file.transferTo(new File(new File(localPath).getAbsolutePath() + "/" + filename));
                String localFilePath = System.getProperty("user.dir") + "/src/main/resources/img/type/" + filename;
//            将保存在本地的头像上传到腾讯云-对象存储
                String key = "zypic/" + filename;
                cosImage.onLoad_img(filename, localFilePath, key);
//            }
//        获取头像的网址
                String http = "https://resource-1316563429.cos.ap-nanjing.myqcloud.com/zypic/" + filename;
                //        执行完毕，删除本地文件
                File localfile = new File(localFilePath);
                localfile.delete();
                result.put("success", http);
                return result;
            }
//            上传文件为空，
            return null;
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }
    }


    //     启用版本 和 停用版本
    @RequestMapping("/useorno")
    @ResponseBody
    public HashMap<String, Object> useOrNo(@RequestBody Map map) {
        try {
            return testTypeDetailsService.useOrNo(map);
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }
    }

    //    TODO 头部测试特殊题目
    @RequestMapping("/headtopic")
    @ResponseBody
    public HashMap<String, Object> headTopic(@RequestBody Map map) {
        try {
            return testTypeDetailsService.headTopic(map);
        } catch (Exception e) {
            HashMap<String, Object> result = new HashMap<>();
            log.error(e.getMessage());
            result.put("result", ERROR);
            return result;
        }
    }


}
